﻿using AntdUI;
using ImportPlcPointPosition.Controls.Base;
using ImportPlcPointPosition.Enums;
using ImportPlcPointPosition.Extensions;
using ImportPlcPointPosition.Utils;
using Mapster;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ImportPlcPointPosition.Controls.Pages
{
    public partial class PlcManagePage : BaseUserControl {
        private readonly SqlSugarClient MesDBClient = SqlSugarHelper.MesDB;
        private BindingList<PlcConfig> DataTableSource = new BindingList<PlcConfig>();

        public PlcManagePage() {
            InitializeComponent();
            this.Load += PlcManagePage_Load;
        }

        #region Methods

        /// <summary>
        /// 初始化表格
        /// </summary>
        private void InitTable() {

            tablePlcList.Columns = new ColumnCollection()
            {
                new ColumnCheck("IsCheck").SetAlign(),
                new Column("Id", "ID").SetAlign().SetEditable(),
                new Column("ProductionLineCode", "产线代号").SetAlign(),
                new Column("WorkstationCode", "工站编号").SetAlign(),
                new Column("PlcAddress", "IP地址").SetAlign(),
                new Column("CpuType", "CPU类型").SetAlign(),
                new Column("RackNumber", "机架号").SetAlign(),
                new Column("SlotNumber", "插槽号").SetAlign(),
                new Column("SortId", "排序").SetAlign(),
                new ColumnCheck("IsEnabled", "启用状态").SetAlign(),
                new ColumnCheck("AgvEnable", "AGV功能").SetAlign(),
                new Column("Remark", "备注").SetAlign(),
                new Column("Operate", "操作").SetAlign().SetFixed(),
            };
            tablePlcList.Bordered = true;
            tablePlcList.EnableHeaderResizing = false;
            tablePlcList.EmptyHeader = true;
            tablePlcList.Gap = 6;
            tablePlcList.EditMode = TEditMode.Click;
            tablePlcList.CellBeginEditInputStyle += Table1_CellBeginEditInputStyle;
            tablePlcList.CellEndEdit += Table1_CellEndEdit;
            tablePlcList.CellButtonClick += Table1_CellButtonClick;
        }

        /// <summary>
        /// 加载数据列表
        /// </summary>
        private void LoadDataTable() {

            DataTableSource.Clear();
            var lst = MesDBClient.Queryable<PlcConfig>()
                .WhereIF(!string.IsNullOrEmpty(this.selLineCode.SelectedValue?.ToString()), o => o.ProductionLineCode == this.selLineCode.SelectedValue.ToString())
                .ToList();
            DataTableSource.AddRange(lst);
            this.tablePlcList.Binding(DataTableSource);
        }

        private void LoadQuerySelect() {
            this.selLineCode.Items.Clear();
            var lst = MesDBClient.Queryable<PlcConfig>().ToList();
            this.selLineCode.Items.AddRange(lst.Select(o => o.ProductionLineCode).Distinct().ToArray());
        }
        #endregion

        #region Events

        /// <summary>
        /// 页面加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlcManagePage_Load(object sender, EventArgs e) {
            InitTable();
            LoadDataTable();
            LoadQuerySelect();
        }

        /// <summary>
        /// 新增行按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNewline_Click(object sender, EventArgs e) {
            var selectValue = (this.selLineCode.SelectedValue) as string;
            if (selectValue != null) {
                DataTableSource.Add(new PlcConfig { ProductionLineCode = selectValue });
                //DataTableSource.AddNew().ProductionLineCode = selectValue;
            } else {
                DataTableSource.AddNew();
            }
        }

        /// <summary>
        /// 刷新按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReflush_Click(object sender, EventArgs e) {
            LoadQuerySelect();
            LoadDataTable();
        }

        /// <summary>
        /// 单元格编辑开始事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Table1_CellBeginEditInputStyle(object sender, TableBeginEditInputStyleEventArgs e) {
            e.Input.SelectAll();//默认选中所有文本
        }

        /// <summary>
        /// 单元格编辑结束事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private bool Table1_CellEndEdit(object sender, TableEndEditEventArgs e) {
            var col = tablePlcList.Columns[e.ColumnIndex];
            if (col.Key == "Id") {
                var old = e.Record as PlcConfig;
                var newid = e.Value.ObjToInt();
                var one = MesDBClient.Queryable<PlcConfig>().Where(a => a.Id == e.Value.ObjToInt()).First();
                if (one != null) {
                    MessageUtils.AlertError(App.MainLayout, "保存失败：Id已经存在");
                    return false;
                }
                MesDBClient.Updateable<PlcConfig>().SetColumns(a => a.Id, newid).Where(a => a.Id == old.Id).ExecuteCommand();
            }
            return true;
        }


        /// <summary>
        /// 单元格操作按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Table1_CellButtonClick(object sender, TableButtonEventArgs e) {
            var item = e.Record as PlcConfig;
            try {
                if (string.IsNullOrEmpty(e.Btn.Id)) {
                    return;
                }
                switch ((eOperateBtnType)Enum.Parse(typeof(eOperateBtnType), e.Btn.Id)) {
                    case eOperateBtnType.AddBtn:
                        break;
                    case eOperateBtnType.EditBtn:
                        break;
                    case eOperateBtnType.DeleteBtn:
                        var result = base.MessageBoxShow($"确认要删除选择的数据吗？", TType.Warn);
                        if (result == DialogResult.OK) {
                            MesDBClient.Deleteable<PlcConfig>().WhereColumns(item, a => new { a.Id }).ExecuteCommand();
                            DataTableSource.Remove(item);
                            base.MessageSuccess("删除成功！");
                            LoadDataTable();
                        }
                        break;
                    case eOperateBtnType.SaveBtn:
                        if (item.Id != 0) {
                            MesDBClient.Updateable<PlcConfig>(item).Where(a => a.Id == item.Id).ExecuteCommand();
                        } else {
                            MesDBClient.Insertable(item).ExecuteCommand();
                        }
                        base.MessageSuccess("保存成功！");
                        LoadDataTable();
                        break;
                    default:
                        break;
                }
            } catch (Exception ex) {
                base.MessageError(ex.Message);
                //throw;
            }
        }

        private void btnSaveAll_Click(object sender, EventArgs e) {
            var list = tablePlcList.DataSource as BindingList<PlcConfig>;
            if (list.Count > 0) {
                foreach (var item in list) {
                    if (item.Id != 0) {
                        MesDBClient.Updateable<PlcConfig>(item).Where(a => a.Id == item.Id).ExecuteCommand();
                    } else {
                        MesDBClient.Insertable(item).ExecuteCommand();
                    }
                }
                base.MessageSuccess("全部保存成功！");
                LoadDataTable();
            }
        }
        #endregion


        private void selLineCode_SelectedIndexChanged(object sender, IntEventArgs e) {

            LoadDataTable();
        }

        private void btnDeleteAll_Click(object sender, EventArgs e) {
            var list = (tablePlcList.DataSource as BindingList<PlcConfig>).Where(o => o.IsCheck).ToList();
            if (list.Count > 0) {
                var result = base.MessageBoxShow($"确认要删除选择的数据吗？", TType.Warn);
                if (result == DialogResult.OK) {
                    MesDBClient.Deleteable(list).ExecuteCommand();
                    base.MessageSuccess("删除成功！");
                    LoadDataTable();
                    LoadQuerySelect();
                }
            } else {
                base.MessageError("请至少选择一行数据！");
            }
        }

        private void btnEnable_Click(object sender, EventArgs e) {

            if (string.IsNullOrEmpty(this.selLineCode.SelectedValue?.ToString())) {
                base.MessageError("请选择产线！");
                return;
            }
            MesDBClient.Updateable<PlcConfig>().SetColumns(o => o.IsEnabled, true).Where(o => o.ProductionLineCode == this.selLineCode.SelectedValue.ToString()).ExecuteCommand();
            LoadDataTable();
        }

        private void btnDeactivate_Click(object sender, EventArgs e) {
            if (string.IsNullOrEmpty(this.selLineCode.SelectedValue?.ToString())) {
                base.MessageError("请选择产线！");
                return;
            }
            MesDBClient.Updateable<PlcConfig>().SetColumns(o => o.IsEnabled, false).Where(o => o.ProductionLineCode == this.selLineCode.SelectedValue.ToString()).ExecuteCommand();
            LoadDataTable();
        }
    }
}
